package com.qf.sportsevent.widget;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2016/12/21.
 */

public class RecyclerItemTouchHelper<D> extends ItemTouchHelper.Callback{
    private List<D> mData;
    private boolean allDragEnable;

    public RecyclerItemTouchHelper(List<D> mData, boolean allDragEnable) {
        this.mData = mData;
        this.allDragEnable = allDragEnable;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags;
        if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
            dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.UP |ItemTouchHelper.RIGHT | ItemTouchHelper.DOWN;
        }else{
            dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        }
        int swipeFlags = 0;
        return makeMovementFlags(dragFlags,swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        int fromPosition = viewHolder.getAdapterPosition();
        int toPosition = target.getAdapterPosition();
        if(fromPosition < toPosition){
            for (int i = fromPosition;i < toPosition;i++){
                Collections.swap(mData,i,i+1);
            }
        }else{
            for (int i = fromPosition;i < toPosition;i--){
                Collections.swap(mData,i,i-1);
            }
        }
        recyclerView.getAdapter().notifyItemMoved(fromPosition,toPosition);
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if(actionState != ItemTouchHelper.ACTION_STATE_IDLE){
            viewHolder.itemView.setAlpha(0.5f);
        }
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        viewHolder.itemView.setAlpha(1f);
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return allDragEnable;
    }
}

